package cn.iocoder.yudao.module.ym.service.area;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.ip.core.Area;
import cn.iocoder.yudao.module.infra.api.ymconnection.dto.ConnectionRespDto;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.module.infra.enums.DictDataConstants;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserImportRespVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleMenuDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.UserRoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.permission.RoleMapper;
import cn.iocoder.yudao.module.system.dal.mysql.permission.RoleMenuMapper;
import cn.iocoder.yudao.module.system.dal.mysql.permission.UserRoleMapper;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.module.ym.controller.admin.site.vo.SiteImportVO;
import cn.iocoder.yudao.module.ym.controller.admin.site.vo.SitePageReqVO;
import cn.iocoder.yudao.module.ym.dal.dataobject.connection.ConnectionDO;
import cn.iocoder.yudao.module.ym.dal.dataobject.site.SimpleSiteDO;
import cn.iocoder.yudao.module.ym.dal.dataobject.site.SiteDO;
import cn.iocoder.yudao.module.ym.dal.mysql.connection.ConnectionMapper;
import cn.iocoder.yudao.module.ym.dal.mysql.site.SiteMapper;
import cn.iocoder.yudao.module.ym.util.CoordinateValidator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.mzt.logapi.context.LogRecordContext;
import com.mzt.logapi.service.impl.DiffParseFunction;
import com.mzt.logapi.starter.annotation.LogRecord;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.ym.controller.admin.area.vo.*;
import cn.iocoder.yudao.module.ym.dal.dataobject.area.AreaDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.ym.dal.mysql.area.AreaMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*;
import static cn.iocoder.yudao.module.system.enums.LogRecordConstants.*;

/**
 * 区域 Service 实现类
 *
 * @author 韩艳阳
 */
@Service
@Validated
public class AreaServiceImpl implements AreaService {

    @Resource
    private AreaMapper areaMapper;

    @Resource
    private SiteMapper siteMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private AdminUserService adminUserService;

    @Resource
    private AdminUserMapper adminUserMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private ConnectionMapper connectionMapper;

    @Override
    public String getNames(String ids) {
        List<AreaDO> areaDOList = areaMapper.selectList();
        String names = "";
        if(ids != null && !"".equals(ids) ){
            for (String s : ids.split(",")) {
                if(!areaDOList.isEmpty()){
                    for (AreaDO areaDO : areaDOList) {
                        if(Long.parseLong(s)==areaDO.getId()){
                            names = names + areaDO.getAreaName() + ",";
                        }
                    }
                }
            }
            if(!names.isEmpty()){
                names = names.substring(0,names.length()-1);
            }
        }

        return names;
    }

    @Override
    public AreaDO getIdByName(String name) {
        return areaMapper.selectOne(new LambdaQueryWrapper<AreaDO>().eq(AreaDO::getAreaName, name));
    }

    @Override
    @Transactional
    @LogRecord(type = YM_AREA_TYPE, subType = YM_AREA_CREATE_SUB_TYPE, bizNo = "{{#area.id}}",
            success = YM_AREA_CREATE_SUCCESS)
    public Long createArea(AreaSaveReqVO createReqVO) {

        AreaDO areaDO = areaMapper.selectOne(new LambdaQueryWrapper<AreaDO>().eq(AreaDO::getAreaName, createReqVO.getAreaName()));
        if(areaDO!=null){
            throw exception(AREA_EXISTS);
        }

        // 插入
        AreaDO area = BeanUtils.toBean(createReqVO, AreaDO.class);
        areaMapper.insert(area);

        //  记录操作日志上下文
        LogRecordContext.putVariable("area", area);


        List<Long> userIds = createReqVO.getBoundUserIds();
        if (userIds!= null && !userIds.isEmpty()) {
            List<ConnectionDO> connectionDOS = new ArrayList<>();
            for (Long userId : userIds) {
                ConnectionDO connectionDO = new ConnectionDO();
                connectionDO.setThingId(area.getId());
                connectionDO.setPeopleId(userId);
                connectionDO.setType(1);
                connectionDOS.add(connectionDO);
            }
            connectionMapper.insertBatch(connectionDOS);
        }
        // 返回
        return area.getId();
    }

    @Override
    @Transactional
    @LogRecord(type = YM_AREA_TYPE, subType = YM_AREA_UPDATE_SUB_TYPE, bizNo = "{{#area.id}}",
            success = YM_AREA_UPDATE_SUCCESS)
    public void updateArea(AreaSaveReqVO updateReqVO) {
        // 校验存在
        AreaDO oldArea = validateAreaExists(updateReqVO.getId());
        Long areaId = updateReqVO.getId();
        AreaDO areaDO = areaMapper.selectOne(new LambdaQueryWrapper<AreaDO>()
                .eq(AreaDO::getAreaName,updateReqVO.getAreaName())
                .ne(AreaDO::getId,updateReqVO.getId())
                .last("LIMIT 1"));
        if (areaDO != null) {
            throw exception(AREA_NAME_ALREADY_EXISTS);
        }

        List<Long> oldUserIds = new ArrayList<>();
        List<ConnectionDO> connectionDOS = connectionMapper.selectList(new LambdaQueryWrapper<ConnectionDO>()
                .eq(ConnectionDO::getThingId,areaId)
                .eq(ConnectionDO::getType,1));
        if (connectionDOS != null && !connectionDOS.isEmpty()) {
            for (ConnectionDO connectionDO : connectionDOS) {
                oldUserIds.add(connectionDO.getPeopleId());
            }
            Map<String,Object> map = new HashMap<>();
            map.put("thing_id",updateReqVO.getId());
            map.put("type",1);
            connectionMapper.deleteByMap(map);
        }

        List<Long> newUserIds = updateReqVO.getBoundUserIds();
        List<ConnectionDO> addConnectionDOS = new ArrayList<>();
        for (Long newUserId : newUserIds) {
            ConnectionDO addConnectionDO = new ConnectionDO();
            addConnectionDO.setType(1);
            addConnectionDO.setThingId(areaId);
            addConnectionDO.setPeopleId(newUserId);
            addConnectionDOS.add(addConnectionDO);
        }
        connectionMapper.insertBatch(addConnectionDOS);



        // 更新
        AreaDO updateObj = BeanUtils.toBean(updateReqVO, AreaDO.class);
        areaMapper.updateById(updateObj);
        //  记录操作日志上下文
        LogRecordContext.putVariable(DiffParseFunction.OLD_OBJECT, BeanUtils.toBean(oldArea, AreaSaveReqVO.class));
        LogRecordContext.putVariable("area", oldArea);
    }

    @Override
    @Transactional
    @LogRecord(type = YM_AREA_TYPE, subType = YM_AREA_DELETE_SUB_TYPE, bizNo = "{{#area.id}}",
            success = YM_AREA_DELETE_SUCCESS)
    public void deleteArea(Long id) {
        // 校验存在
        AreaDO areaDO = validateAreaExists(id);
        SiteDO siteDO = siteMapper.selectOne(new LambdaQueryWrapper<SiteDO>()
                .eq(SiteDO::getAreaId,id)
                .last("LIMIT 1"));
        if (siteDO == null) {
            // 删除
            areaMapper.deleteById(id);
            Map<String,Object> map = new HashMap<>();
            map.put("thing_id",id);
            map.put("type",1);
            connectionMapper.deleteByMap(map);
            //  记录操作日志上下文
            LogRecordContext.putVariable("area", areaDO);
        }else {
            throw exception(SITE_UNDER_AREA_EXISTS);
        }
    }

    private AreaDO validateAreaExists(Long id) {
        AreaDO areaDO = areaMapper.selectById(id);
        if (areaDO == null) {
            throw exception(AREA_NOT_EXISTS);
        }
        return areaDO;
    }

    @Override
    public AreaRespVO getArea(Long id) {
        AreaDO areaDO = areaMapper.selectById(id);
        AreaRespVO areaRespVO =BeanUtil.toBean(areaDO, AreaRespVO.class);

        List<Long> oldUserIds = new ArrayList<>();
        List<ConnectionDO> connectionDOS = connectionMapper.selectList(new LambdaQueryWrapper<ConnectionDO>()
                .eq(ConnectionDO::getThingId,id)
                .eq(ConnectionDO::getType,1));
        if (connectionDOS != null) {
            for (ConnectionDO connectionDO : connectionDOS) {
                oldUserIds.add(connectionDO.getPeopleId());
            }
            connectionMapper.deleteByIds(oldUserIds);
        }
        areaRespVO.setBoundUserIds(oldUserIds);

        return areaRespVO;
    }

    @Override
    public List<AreaRespVO> getAreaListAll(AreaPageReqVO pageReqVO) {


        List<AreaRespVO> areaRespVOList = new ArrayList<>();

        areaRespVOList = BeanUtils.toBean(areaMapper.selectList(pageReqVO), AreaRespVO.class);

        List<SiteDO> siteDOS = siteMapper.selectList(new SitePageReqVO());


        Map<Long, List<SiteDO>> map = siteDOS.stream()
                .filter(site -> site.getAreaId() != null)
                .collect(Collectors.groupingBy(SiteDO::getAreaId));

        if(areaRespVOList != null && !areaRespVOList.isEmpty()){
            for (AreaRespVO areaRespVO : areaRespVOList) {
                List<SiteDO> siteDOS1 = map.get(areaRespVO.getId());
                if(siteDOS1 != null){
                    List<SimpleSiteDO> SimpleSiteDOS = BeanUtils.toBean(siteDOS1, SimpleSiteDO.class);
                    areaRespVO.setSimpleSiteDOList(SimpleSiteDOS);
                }
            }
        }

        return areaRespVOList;
    }

    @Override
    public List<AreaRespVO> getAreaList(AreaPageReqVO pageReqVO) {
        Long loginUserId = getLoginUserId();
        Long userId = pageReqVO.getUserId();
        if(userId != null){
            loginUserId = userId;
        }
        //查看当前用户是否有查看所有数据的权限
        Boolean flag = handleAll(loginUserId);

        List<AreaRespVO> areaRespVOList = new ArrayList<>();

        Set<Long> areaSet = new HashSet<>();
        Set<Long> siteSet = new HashSet<>();
        //判断是不是管理员，只有管理员才可以查看所有的区域和电站，其它的只能查看自己负责的(有关的)
        if(flag){
            areaRespVOList = BeanUtils.toBean(areaMapper.selectList(pageReqVO), AreaRespVO.class);

            List<SiteDO> siteDOS = siteMapper.selectList(new SitePageReqVO());


            Map<Long, List<SiteDO>> map = siteDOS.stream()
                    .filter(site -> site.getAreaId() != null)
                    .collect(Collectors.groupingBy(SiteDO::getAreaId));

            if(areaRespVOList != null && !areaRespVOList.isEmpty()){
                for (AreaRespVO areaRespVO : areaRespVOList) {
                    List<SiteDO> siteDOS1 = map.get(areaRespVO.getId());
                    if(siteDOS1 != null){
                        List<SimpleSiteDO> SimpleSiteDOS = BeanUtils.toBean(siteDOS1, SimpleSiteDO.class);
                        areaRespVO.setSimpleSiteDOList(SimpleSiteDOS);
                    }
                }
            }
        }else {

            //查看当前用户是否有查看所有电站的数据权限
            Boolean siteAll = handleSiteAll(loginUserId);

            AdminUserDO user = adminUserService.getUser(loginUserId);
            if(user != null){
                String areaIds = user.getAreaIds();
                String siteIds = user.getSiteIds();
                if(areaIds != null && !areaIds.isEmpty()){
                    areaSet = Arrays.stream(areaIds.split(","))
                            .map(String::trim)
                            .map(Long::parseLong)    // 转为 Long
                            .collect(Collectors.toSet());
                }
                if(siteIds != null && !siteIds.isEmpty()){
                    siteSet = Arrays.stream(siteIds.split(","))
                            .map(String::trim)
                            .map(Long::parseLong)    // 转为 Long
                            .collect(Collectors.toSet());
                }
            }
            if(!areaSet.isEmpty()){
                pageReqVO.setIds(areaSet);
            }
            areaRespVOList = BeanUtils.toBean(areaMapper.selectList(pageReqVO), AreaRespVO.class);

            if(areaRespVOList != null && !areaRespVOList.isEmpty()){
                SitePageReqVO sitePageReqVO = new SitePageReqVO();
                //查看和自己有关的电站
                if(siteSet!= null && !siteSet.isEmpty()){
                    sitePageReqVO.setIds(siteSet);
                }

                List<SiteDO> siteDOS = siteMapper.selectList(sitePageReqVO);


                for (AreaRespVO areaRespVO : areaRespVOList) {
                    //判断该用户是否有查看全部电站的权限，如果没有则只能查看已经上线的电站
                    if(!siteAll){
                        Map<Long, List<SiteDO>> map = siteDOS.stream()
                                .filter(site -> site.getAreaId() != null)
                                .filter(site -> Objects.equals(site.getSiteStatus(), DictDataConstants.YM_SITE_STATUS_5))
                                .collect(Collectors.groupingBy(SiteDO::getAreaId));
                        List<SiteDO> siteDOS1 = map.get(areaRespVO.getId());
                        if(siteDOS1 != null){
                            List<SimpleSiteDO> SimpleSiteDOS = BeanUtils.toBean(siteDOS1, SimpleSiteDO.class);
                            areaRespVO.setSimpleSiteDOList(SimpleSiteDOS);
                        }
                    }else {
                        Map<Long, List<SiteDO>> map = siteDOS.stream()
                                .filter(site -> site.getAreaId() != null)
                                .collect(Collectors.groupingBy(SiteDO::getAreaId));
                        List<SiteDO> siteDOS1 = map.get(areaRespVO.getId());
                        if(siteDOS1 != null){
                            List<SimpleSiteDO> SimpleSiteDOS = BeanUtils.toBean(siteDOS1, SimpleSiteDO.class);
                            areaRespVO.setSimpleSiteDOList(SimpleSiteDOS);
                        }
                    }

                }
            }

        }

        return areaRespVOList;
    }

    @Override
    public PageResult<AreaRespVO> getAreaPage(AreaPageReqVO pageReqVO) {
        Long loginUserId = getLoginUserId();
        Long userId = pageReqVO.getUserId();
        if(userId != null){
            loginUserId = userId;
        }
        //查看当前用户是否有查看所有数据的权限
        Boolean flag = handleAll(loginUserId);

        PageResult<AreaRespVO> areaRespVOPageResult = new PageResult<>();

        Set<Long> areaSet = new HashSet<>();
        Set<Long> siteSet = new HashSet<>();

        if(flag){
            areaRespVOPageResult = BeanUtils.toBean(areaMapper.selectPage(pageReqVO), AreaRespVO.class);

            List<AreaRespVO> areaRespVOList = areaRespVOPageResult.getList();

            List<SiteDO> siteDOS = siteMapper.selectList(new SitePageReqVO());
            Map<Long, List<SiteDO>> map = siteDOS.stream()
                    .filter(site -> site.getAreaId() != null)
                    .collect(Collectors.groupingBy(SiteDO::getAreaId));

            if(areaRespVOList != null && !areaRespVOList.isEmpty()){
                for (AreaRespVO areaRespVO : areaRespVOList) {
                    List<SiteDO> siteDOS1 = map.get(areaRespVO.getId());
                    if(siteDOS1 != null){
                        List<SimpleSiteDO> SimpleSiteDOS = BeanUtils.toBean(siteDOS1, SimpleSiteDO.class);
                        areaRespVO.setSimpleSiteDOList(SimpleSiteDOS);
                    }
                }
            }
        }else {

            //查看当前用户是否有查看所有电站的数据权限
            Boolean siteAll = handleSiteAll(loginUserId);

            AdminUserDO user = adminUserService.getUser(loginUserId);
            if(user != null){
                String areaIds = user.getAreaIds();
                String siteIds = user.getSiteIds();
                if(areaIds != null && !areaIds.isEmpty()){
                    areaSet = Arrays.stream(areaIds.split(","))
                            .map(String::trim)
                            .map(Long::parseLong)    // 转为 Long
                            .collect(Collectors.toSet());
                }
                if(siteIds != null && !siteIds.isEmpty()){
                    siteSet = Arrays.stream(siteIds.split(","))
                            .map(String::trim)
                            .map(Long::parseLong)    // 转为 Long
                            .collect(Collectors.toSet());
                }
            }

            if(areaSet!= null && !areaSet.isEmpty()){
                pageReqVO.setIds(areaSet);
            }
            areaRespVOPageResult = BeanUtils.toBean(areaMapper.selectPage(pageReqVO), AreaRespVO.class);
            List<AreaRespVO> areaRespVOList = areaRespVOPageResult.getList();

            if(areaRespVOList != null && !areaRespVOList.isEmpty()){
                SitePageReqVO sitePageReqVO = new SitePageReqVO();
                //查看和自己有关的电站
                if(siteSet!= null && !siteSet.isEmpty()){
                    sitePageReqVO.setIds(siteSet);
                }

                List<SiteDO> siteDOS = siteMapper.selectList(sitePageReqVO);


                for (AreaRespVO areaRespVO : areaRespVOList) {
                    //判断该用户是否有查看全部电站的权限，如果没有则只能查看已经上线的电站
                    if(!siteAll){
                        Map<Long, List<SiteDO>> map = siteDOS.stream()
                                .filter(site -> site.getAreaId() != null)
                                .filter(site -> Objects.equals(site.getSiteStatus(), DictDataConstants.YM_SITE_STATUS_5))
                                .collect(Collectors.groupingBy(SiteDO::getAreaId));
                        List<SiteDO> siteDOS1 = map.get(areaRespVO.getId());
                        if(siteDOS1 != null){
                            List<SimpleSiteDO> SimpleSiteDOS = BeanUtils.toBean(siteDOS1, SimpleSiteDO.class);
                            areaRespVO.setSimpleSiteDOList(SimpleSiteDOS);
                        }
                    }else {
                        Map<Long, List<SiteDO>> map = siteDOS.stream()
                                .filter(site -> site.getAreaId() != null)
                                .collect(Collectors.groupingBy(SiteDO::getAreaId));
                        List<SiteDO> siteDOS1 = map.get(areaRespVO.getId());
                        if(siteDOS1 != null){
                            List<SimpleSiteDO> SimpleSiteDOS = BeanUtils.toBean(siteDOS1, SimpleSiteDO.class);
                            areaRespVO.setSimpleSiteDOList(SimpleSiteDOS);
                        }
                    }

                }
            }

        }

        return areaRespVOPageResult;
    }

    /**
     * 判断当前用户是否 管理员
     * @param userId
     * @return
     */
    public Boolean handleAll(Long userId){
        //判断当前用户得权限  如果是tenant_admin 则查看全部数据
        List<UserRoleDO> userRoleDOS = userRoleMapper.selectListByUserId(userId);
        if(userRoleDOS!=null && !userRoleDOS.isEmpty()){
            for (UserRoleDO userRoleDO : userRoleDOS) {
                Long roleId = userRoleDO.getRoleId();
                RoleDO roleDO = roleMapper.selectById(roleId);
                if(roleDO!=null && roleDO.getCode().equals("tenant_admin")){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断当前用户是否 具有查看所有状态电站的权限
     * @param userId
     * @return
     */
    public Boolean handleSiteAll(Long userId){
        //2807	查看全部电站	yn:site:all
        //2808	查看已上线电站	ym:site_online
        List<UserRoleDO> userRoleDOS = userRoleMapper.selectListByUserId(userId);
        if(userRoleDOS != null && !userRoleDOS.isEmpty()){
            for (UserRoleDO userRoleDO : userRoleDOS) {
                Long roleId = userRoleDO.getRoleId();
                RoleDO roleDO = roleMapper.selectById(roleId);
                if(roleDO != null){
                    List<RoleMenuDO> roleMenuDOS = roleMenuMapper.selectListByRoleId(roleDO.getId());
                    if(roleMenuDOS != null && !roleMenuDOS.isEmpty()){
                        for (RoleMenuDO roleMenuDO : roleMenuDOS) {
                            if(roleMenuDO.getMenuId() == 2807){
                                return true;
                            }
                        }
                    }
                }
            }
        }
        return false;
    }

    @Override
    @Transactional
    @LogRecord(type = YM_AREA_TYPE, subType = YM_AREA_IMPORT_SUB_TYPE, bizNo = "1",
            success = YM_AREA_IMPORT_SUCCESS)
    public UserImportRespVO importArea(List<Map<String,String>> dataList,boolean isUpdateSupport){

        List<AreaDO> inserList = new ArrayList<>();
        List<AreaDO> updateAreaList = new ArrayList<>();


        //校验参数
        if (CollUtil.isEmpty(dataList)){
            throw exception(AREA_IMPORT_LIST_IS_EMPTY);
        }
        //转Excel数据到VO对象
        List<AreaImportVO> importList = convertToImportVO(dataList);
        if (importList.isEmpty()) {
            throw exception(AREA_IMPORT_LIST_IS_EMPTY);
        }
        //判断导入的区域名字是否有重复的
        Map<String, Integer> keyCountMap = new HashMap<>();
        for (AreaImportVO areaImportVO : importList) {
            String areaName = areaImportVO.getAreaName();
            if (areaName == null) {
                throw exception(AREA_NAME_NOT_EXISTS);
            }
            if(keyCountMap.get(areaName) != null){
                throw exception(new ErrorCode(1_001_201_034, String.format("EXCEL- %s 区域名字重复",areaName)));
            }
            String coordinates = areaImportVO.getCoordinates();
            if(!CoordinateValidator.isValidCoordinateString(coordinates)){
                throw exception(new ErrorCode(1_002_000_001, "Excel格式错误,请检查区域名称是否为空以及坐标集合是否格式正确!"));
            }
            keyCountMap.put(areaName,1);
        }

        List<AreaDO> areaDOList = areaMapper.selectList();
        // 正确转换方式
        Map<String, AreaDO> areaMap = Optional.ofNullable(areaDOList)
                .orElseGet(Collections::emptyList) // 处理null列表
                .stream()
                .filter(areaDO -> areaDO.getAreaName() != null)
                .collect(Collectors.toMap(
                        AreaDO::getAreaName,  // Key提取器
                        Function.identity(),  // Value提取器（对象本身）
                        (oldValue, newValue) -> oldValue  // 处理重复键：保留第一个值
                ));

        //导入逻辑
        UserImportRespVO respVO = UserImportRespVO.builder()
                .createUsernames(new ArrayList<>())
                .updateUsernames(new ArrayList<>())
                .failureUsernames(new LinkedHashMap<>()).build();


        importList.forEach(vo ->{
            try {


                AreaDO existArea = areaMap.get(vo.getAreaName());

                if(existArea == null){
                    inserList.add(BeanUtil.toBean(vo,AreaDO.class));
//                    respVO.getCreateUsernames().add(vo.getAreaName());
                    respVO.getCreateUsernames().add("1");
                }else if(isUpdateSupport){
                    AreaDO updateDO = BeanUtil.toBean(vo,AreaDO.class);
                    updateDO.setId(existArea.getId());
                    updateAreaList.add(updateDO);
//                    respVO.getUpdateUsernames().add(vo.getAreaName());
                    respVO.getUpdateUsernames().add("1");
                }else {
                    respVO.getFailureUsernames().put(vo.getAreaName(), "区域已存在且不允许更新");
                }

            }catch (Exception e){
                respVO.getFailureUsernames().put(vo.getAreaName(), "系统错误: " + e.getMessage());
            }

        });
        if(!inserList.isEmpty()){
            areaMapper.insertBatch(inserList,5000);
        }

        if(!updateAreaList.isEmpty()){
            areaMapper.updateBatch(updateAreaList,5000);
        }

        return respVO;
    }

    @Override
    public List<AdminUserDO> getAreaUser(Long areaId){

        List<ConnectionDO> connectionDOS = connectionMapper.selectList(new LambdaQueryWrapper<ConnectionDO>()
                .eq(ConnectionDO::getThingId,areaId)
                .eq(ConnectionDO::getType,1)
        );
        if (connectionDOS!= null && !connectionDOS.isEmpty()) {
            List<Long> userIds = new ArrayList<>();
            for (ConnectionDO connectionDO : connectionDOS) {
                Long userId = connectionDO.getPeopleId();
                userIds.add(userId);
            }
            return adminUserService.getUserList(userIds);
        }else {
            throw exception(AREA_NOT_PEOPLE);
        }
    }

    private List<AreaImportVO> convertToImportVO(
            List<Map<String, String>> dataList
    ){
        try{
            List<AreaImportVO> areaImportVOS = new ArrayList<>();
            for (Map<String, String> data : dataList) {
                AreaImportVO vo = new AreaImportVO();
                vo.setAreaName( data.get("区域名称"));
                vo.setAreaDescription(data.get("区域描述"));
                vo.setCoordinates( data.get("坐标集合"));
                areaImportVOS.add(vo);
            }
            return areaImportVOS;
        }catch (Exception e){
            throw exception(AREA_IMPORT_FALSE);
        }

    }


}
